package com.trg.flex.frm
{
	import com.trg.flex.frm.validation.InputValidationHelper;
	
	import flash.display.DisplayObject;
	import flash.events.FocusEvent;
	
	import mx.controls.CheckBox;
	import mx.events.FlexEvent;

	[Event(name="validChanged", type="mx.events.PropertyChangeEvent")]
	public final class FormCheckBox extends CheckBox implements FormInput
	{
		protected var formContainer:FormContainer;
		protected var topContainer:DisplayObject;
		protected var _property:String;
		
		public function FormCheckBox()
		{
			super();
			topContainer = this;
			topContainer.addEventListener(FlexEvent.ADD, addListener);
			
		}
		
		protected function addListener(event : FlexEvent) : void {
			topContainer.removeEventListener(FlexEvent.ADD, addListener);
			
			while(true) {
				if (topContainer.parent is FormContainer) {
					formContainer = topContainer.parent as FormContainer;
					formContainer.addElement(this);
					break;
				} else if (topContainer.parent == null) {
					topContainer.addEventListener(FlexEvent.ADD, addListener);
					break;
				}
				topContainer = topContainer.parent;
			}
		}
		
		public function get elementValue() : Object {
			return selected;
		}
		
		public function set elementValue(value : Object) : void {
			selected = Boolean(value);
			validationHelper.setNotValidated();
		}
		
		public function get property() : String {
			return _property;
		}
		
		public function set property(property : String) : void {
			_property = property;
		}
		
	//Validation
		protected var validationHelper:InputValidationHelper = new InputValidationHelper(this as FormInput, "selected", FlexEvent.VALUE_COMMIT, FocusEvent.FOCUS_OUT);
		
		[Bindable("validChanged")]
		public function get valid():Boolean {
			return validationHelper.valid;
		}
		
		public function isInvalidRequired():Boolean {
			return validationHelper.isInvalidRequired();
		}
		
		public function clearValidation():void {
			errorString = "";
		}
		
		public function set type(value:Class):void {
			validationHelper.type = value;
		}
		
		public function setMetaData(metaData:Object):void {
			validationHelper.setMetaData(metaData);
		}
		
		public function set assertTrue(value:Boolean):void {
			validationHelper.setMetaDataProp("assertTrue", value ? true : undefined);
		}
		
		public function set assertFalse(value:Boolean):void {
			validationHelper.setMetaDataProp("assertFalse", value ? true : undefined);
		}

	}
}